<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="车间编码" prop="workshopCode">
        <el-input v-model="searchForm.workshopCode" placeholder="请输入车间编码" clearable />
      </el-form-item>
      <el-form-item label="车间名称" prop="workshopName">
        <el-input v-model="searchForm.workshopName" placeholder="请输入车间名称" clearable />
      </el-form-item>
      <el-form-item label="所属工厂" prop="factoryId">
        <el-select v-model="searchForm.factoryId" placeholder="请选择工厂" clearable style="width: 180px">
          <el-option
            v-for="factory in factoryOptions"
            :key="factory.id"
            :label="factory.factoryName"
            :value="factory.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车间类型" prop="workshopType">
        <el-select v-model="searchForm.workshopType" placeholder="请选择类型" clearable style="width: 180px">
          <el-option label="生产车间" value="PRODUCTION" />
          <el-option label="装配车间" value="ASSEMBLY" />
          <el-option label="质检车间" value="QUALITY" />
          <el-option label="仓储车间" value="WAREHOUSE" />
        </el-select>
      </el-form-item>
      <el-form-item label="车间状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
          <el-option label="维护中" value="MAINTENANCE" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增车间</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="workshopCode" label="车间编码" />
      <el-table-column prop="workshopName" label="车间名称" />
      <el-table-column prop="factoryName" label="所属工厂" />
      <el-table-column prop="workshopType" label="车间类型">
        <template #default="scope">
          <el-tag :type="getTypeColor(scope.row.workshopType)">{{ getTypeText(scope.row.workshopType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="area" label="面积(㎡)" />
      <el-table-column prop="manager" label="负责人" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" />
      <el-table-column label="操作" width="350" fixed="right">
        <template #default="scope">
          <el-button type="primary" link :icon="View" @click="handleView(scope.row)" class="operation-btn">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)" class="operation-btn">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)" class="operation-btn">删除</el-button>

          <!-- 更多操作下拉菜单 -->
          <el-dropdown @command="handleMoreAction" trigger="click">
            <el-button type="primary" link class="operation-btn">
              更多 <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="{ action: 'enable', row: scope.row }" v-if="scope.row.status !== 'ACTIVE'">
                  <el-icon><check /></el-icon>
                  启用
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'disable', row: scope.row }" v-if="scope.row.status !== 'INACTIVE'">
                  <el-icon><close /></el-icon>
                  禁用
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'maintenance', row: scope.row }" v-if="scope.row.status !== 'MAINTENANCE'">
                  <el-icon><tools /></el-icon>
                  维护
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 车间表单抽屉 -->
    <WorkshopForm ref="formDrawerRef" />
  </div>
</template>

<script setup lang="ts" name="workshopTable">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, EditPen, View, ArrowDown, Check, Close, Tools } from "@element-plus/icons-vue";
import WorkshopForm from "./form.vue";
import { PageHelper } from "@/utils/pageHelper";
import {
  getWorkshopList,
  enableWorkshop,
  disableWorkshop,
  setWorkshopMaintenance,
  deleteWorkshop,
  type Workshop
} from "@/api/modules/workshop";
import { getFactoryList, type Factory } from "@/api/modules/factory";

const loading = ref(false);
const tableData = ref<Workshop.WorkshopListItem[]>([]);
const searchFormRef = ref<FormInstance>();
const factoryOptions = ref<Factory.FactoryListItem[]>([]);

// 查询表单
const searchForm = reactive({
  workshopCode: "",
  workshopName: "",
  factoryId: null as number | null,
  workshopType: "",
  status: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: "success",
    INACTIVE: "warning",
    MAINTENANCE: "info"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: "启用",
    INACTIVE: "禁用",
    MAINTENANCE: "维护中"
  };
  return statusMap[status] || status;
};

// 获取类型颜色
const getTypeColor = (type: string) => {
  const typeMap: Record<string, string> = {
    PRODUCTION: "primary",
    ASSEMBLY: "success",
    QUALITY: "warning",
    WAREHOUSE: "info"
  };
  return typeMap[type] || "info";
};

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    PRODUCTION: "生产车间",
    ASSEMBLY: "装配车间",
    QUALITY: "质检车间",
    WAREHOUSE: "仓储车间"
  };
  return typeMap[type] || type;
};

// 获取工厂选项
const getFactoryOptions = async () => {
  try {
    const res = await getFactoryList({ current: 1, size: 1000 });
    const pageData = PageHelper.parsePage<Factory.FactoryListItem>(res.data);
    factoryOptions.value = pageData.records;
  } catch (error) {
    console.error("获取工厂列表失败:", error);
  }
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = PageHelper.createPageParams(pagination.currentPage, pagination.pageSize, searchForm);
    const res = await getWorkshopList(params);

    // 使用PageHelper安全解析分页数据
    const pageData = PageHelper.parsePage<Workshop.WorkshopListItem>(res.data);
    tableData.value = pageData.records;
    pagination.total = pageData.total;

    console.log("解析后的分页数据:", pageData);
  } catch (error) {
    console.error("获取车间列表失败:", error);
    ElMessage.error("获取车间列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 车间表单抽屉引用
const formDrawerRef = ref<InstanceType<typeof WorkshopForm>>();

// 新增车间
const handleAdd = () => {
  const params = {
    title: "新增",
    isView: false,
    row: {},
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

const handleView = (row: Workshop.WorkshopListItem) => {
  const params = {
    title: "查看",
    isView: true,
    row: { ...row },
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 编辑车间
const handleEdit = (row: Workshop.WorkshopListItem) => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...row },
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 启用车间
const handleEnable = async (row: Workshop.WorkshopListItem) => {
  try {
    await enableWorkshop(row.id);
    ElMessage.success("车间启用成功");
    getTableData();
  } catch (error) {
    console.error("车间启用失败:", error);
    ElMessage.error("车间启用失败");
  }
};

// 禁用车间
const handleDisable = async (row: Workshop.WorkshopListItem) => {
  try {
    await disableWorkshop(row.id);
    ElMessage.success("车间禁用成功");
    getTableData();
  } catch (error) {
    console.error("车间禁用失败:", error);
    ElMessage.error("车间禁用失败");
  }
};

// 设置维护状态
const handleMaintenance = async (row: Workshop.WorkshopListItem) => {
  try {
    await setWorkshopMaintenance(row.id);
    ElMessage.success("车间设置维护状态成功");
    getTableData();
  } catch (error) {
    console.error("车间设置维护状态失败:", error);
    ElMessage.error("车间设置维护状态失败");
  }
};

// 删除车间
const handleDelete = async (row: Workshop.WorkshopListItem) => {
  ElMessageBox.confirm(`确认删除车间 "${row.workshopName}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteWorkshop(row.id);
        ElMessage.success("车间删除成功");
        getTableData();
      } catch (error) {
        console.error("车间删除失败:", error);
        ElMessage.error("车间删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 处理更多操作下拉菜单
const handleMoreAction = (command: { action: string; row: Workshop.WorkshopListItem }) => {
  const { action, row } = command;

  switch (action) {
    case "enable":
      handleEnable(row);
      break;
    case "disable":
      handleDisable(row);
      break;
    case "maintenance":
      handleMaintenance(row);
      break;
    default:
      console.warn("未知的操作类型:", action);
  }
};

// 页面加载时获取数据
onMounted(() => {
  getFactoryOptions();
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.el-table {
  flex: 1;
}

:deep(.el-table__row) {
  height: 30px !important;
  line-height: 35px;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}

:deep(.el-table__header-row) {
  height: 65px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.operation-btn) {
  font-size: 14px;
  margin: 0 2px;
}

:deep(.operation-btn .el-icon) {
  font-size: 16px;
  margin-right: 2px;
}
</style>